import { Consts, createAPI } from './fetchRequest';

export function createUrl(url) {
  const baseUrl = __HOST__;
  
  if (url) {
    return `${baseUrl}/api/${url}`;
  }
  
  return baseUrl;
}

function fetchRequest(HttpMethod, url, params, options) {
  const defaultOptions = {
    mode: 'cors',
    credentials: 'include',
    headers: {
      'x-requested-with': 'XMLHttpRequest'
    }
  };
  
  if (params) {
    defaultOptions.body = { ...params };
  }
  
  const requestOptions = Object.assign({}, defaultOptions, options);
  const contentType = requestOptions.headers['Content-Type'];
  
  if (contentType && contentType === 'application/json' && requestOptions.body) {
    requestOptions.body = JSON.stringify(requestOptions.body);
  }

  const request = createAPI(HttpMethod, createUrl(url), requestOptions);
  return request();
}

export default {
  get(url, params = {}, options = {}) {
    return fetchRequest(Consts.HttpMethods.GET, url, params, options);
  },
  post(url, params = {}, options = {}) {
    const headers = {
      'Content-Type': 'application/json'
    };
    return fetchRequest(Consts.HttpMethods.POST, url, params, Object.assign({ headers }, options));
  }
};
